﻿using ETWJ.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ETWJ.Service
{
    public class BaseService<T> where T : BaseModel
    {
        private MyDbContext ctx;
        //public BaseService() { }

        public BaseService(MyDbContext ctx)
        {
            this.ctx = ctx;
        }
       

        public  IQueryable<T> GetAll()
        {
            return  ctx.Set<T>().Where(e => e.IsDeleted == 0);
        }


        public IQueryable<T> GetByPage(int pageIndex,int count)
        {
            return ctx.Set<T>().Where(e => e.IsDeleted == 0).Skip((pageIndex - 1) * count).Take(count);
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await GetAll().Where(e => e.Id == id).SingleOrDefaultAsync();
        }

        public async Task<int> MarkDeleted(int id)
        {
            var res =await GetByIdAsync(id);
            if (res != null)
            {
                res.IsDeleted = 1;
                return await ctx.SaveChangesAsync();
            }
            return 0;
        }

        public  async Task RealDeleted(int id)
        {
            var res = await GetByIdAsync(id);
            if(res!=null)
            {
                using (MyDbContext ctx = new MyDbContext())
                {
                    ctx.Set<T>().Remove(res);
                    await ctx.SaveChangesAsync();
                }
            }
        }


        public async Task<int> AddNew(T t)
        {
            ctx.Set<T>().Add(t);
            return await ctx.SaveChangesAsync();
        }

        public async Task<int> GetCount()
        {
            return await GetAll().CountAsync<T>();
        }

       

    }
}
